const Router = require('koa-router');
const router = new Router();
const mongoose = require('mongoose');

//发送token,解密token
const jwt = require('jsonwebtoken');
const jwtKoa = require('koa-jwt');
const util = require('util');
const verify = util.promisify(jwt.verify) // 解密
const secret = 'jwt demo';

router.post('/item',async (ctx)=>{
    const token = ctx.header.authorization  // 获取jwt
    
    let payload = null;
        if (token) {
            payload = await verify(token.split(' ')[1], secret)  // // 解密，获取payload
        } else {
            ctx.body = {
                message: 'token 错误',
                code: -1
            };
            return false;
        }
    let content = mongoose.model('Content');
    let newItem = new content(ctx.request.body);
    await newItem.save().then(()=>{
        ctx.body = {
            code:200,
            payload,
            msg:'发布成功!'
        }
    }).catch((error)=>{
        ctx.body = {
            code:500,
            msg:'发布失败!'
        }
    })
});
router.get('/allItem',async (ctx)=>{ 
    let content = mongoose.model('Content');
    await content.find({}).exec().then((resl)=>{
        ctx.body = {
            code:200,
            data:resl
        }
    }).catch((error)=>{
        ctx.body = {
            code:500,
            data:[]
        }
    });
});

module.exports = router;